package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrType;

public class SIDMAC extends AxdrType {
    private byte[] dataCode = null;
    private SID sid = null;
    private MAC mac = null;

    public SIDMAC() {
    }

    public byte[] getDataCode() {
        return dataCode;
    }

    public SID getSid() {
        return sid;
    }

    public MAC getMac() {
        return mac;
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(SID sid, MAC mac) {
        this.sid = sid;
        this.mac = mac;
    }

    public void setSID(SID sid) {
        this.sid = sid;
    }

    public void setMAC(MAC mac) {
        this.mac = mac;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.sid = new SID();
        codeLength += this.sid.decode(input);
        this.mac = new MAC();
        codeLength += this.mac.decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.sid != null && this.mac != null) {
                codeLength = 0;
                codeLength += this.sid.encode(output);
                codeLength += this.mac.encode(output);
            } else {
                throw new Exception("SID or MAC is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.toByteArray();
    }

    @Override
    public String toString() {
        if (this.sid != null && this.mac != null) {
            return "sequence: {" + "sid: " + this.sid + ", mac: " + this.mac + "}";
        } else {
            return "SID or MAC is null";
        }
    }
}



